#include "usermanagementwidget.h"
#include "ui_usermanagementwidget.h"
#include "sessionmanager.h"
#include "accountmanager.h"

void loadAllFlights(const QString& folderPath);



MatrixGraph g;
QString Path = "C:\\Users\\LEO\\Desktop\\study\\QT\\allFlightsData";

UserManagementWidget::UserManagementWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserManagementWidget)
{
    ui->setupUi(this);

    loadAllFlights(Path);

    // 设置TableWidget列名
    QStringList headers = {"起、降城市", "日期", "总价", "航班号", "航空公司", "从城市飞往", "降落", "起飞机场",
                           "降落机场", "起飞时间", "到达时间", "价格", "改签", "增值服务", "服务价格"};
    ui->bookingTableWidget->setColumnCount(headers.size());
    ui->bookingTableWidget->setHorizontalHeaderLabels(headers);

    connect(ui->mapButton,&QPushButton::clicked,this,&UserManagementWidget::openMap);
    // 加载当前用户信息
    loadUserInfo();
}


UserManagementWidget::~UserManagementWidget()
{
    delete ui;
}

// 加载当前用户信息
void UserManagementWidget::loadUserInfo() {
    QString userID = SessionManager::getUserID();
    if (userID.isEmpty()) {
        qDebug() << "No user found with id: " << userID;
        return;
    }

    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    QSqlQuery query(db);
    query.prepare("SELECT username, contact FROM users WHERE id = ?");
    query.addBindValue(userID);

    if (!query.exec()) {
        qDebug() << "Failed to execute query in loadUserInfo: " << query.lastError().text();
        return;
    }

    if (query.next()) {
        QString username = query.value(0).toString();
        QString contact = query.value(1).toString();

        ui->usernameLabel->setText(username);
        ui->contactLabel->setText(contact);
    } else {
        qDebug() << "No user found with id: " << userID;
    }

    loadBookingHistory();
}


void UserManagementWidget::loadBookingHistory() {
    QString userID = SessionManager::getUserID();
    if (userID.isEmpty()) {
        qDebug() << "No user found with id: " << userID;
        return;
    }

    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    // 查询用户的预订信息以及每个 journey 相关的 segments
    QSqlQuery query(db);
    query.prepare("SELECT ub.booking_id, j.journey_id, fs.segment_id, j.start_city, j.end_city, j.total_price, j.travel_date, fs.flight_number, fs.airline, fs.from_city, fs.to_city, "
                  "fs.departure_airport, fs.arrival_airport, fs.departure_time, fs.arrival_time, fs.price, fs.is_transfer, fs.special_services, fs.service_price "
                  "FROM user_bookings ub "
                  "JOIN journeys j ON ub.journey_id = j.journey_id "
                  "JOIN flight_segments fs ON j.journey_id = fs.journey_id "
                  "WHERE ub.user_id = :userID "
                  "ORDER BY ub.booking_id, fs.departure_time");
    query.bindValue(":userID", userID);

    if (!query.exec()) {
        qDebug() << "Failed to execute query in loadBookingHistory: " << query.lastError().text();
        return;
    }

    ui->bookingTableWidget->setRowCount(0);  // 清空现有行数

    int currentJourneyID = -1; // 用于标记当前的 journey_id
    int row = -1;

    // 使用一个集合来追踪已经插入的航段，避免重复显示
    QSet<QString> displayedSegments;  // 改为 QSet<QString>

    while (query.next()) {
        int bookingID = query.value(0).toInt();
        int journeyID = query.value(1).toInt();
        int segmentID = query.value(2).toInt();
        QString startCity = query.value(3).toString();
        QString endCity = query.value(4).toString();
        double totalPrice = query.value(5).toDouble();
        QString traveldate = query.value(6).toString();
        QString flightNumber = query.value(7).toString();
        QString airline = query.value(8).toString();
        QString fromCity = query.value(9).toString();
        QString toCity = query.value(10).toString();
        QString departureAirport = query.value(11).toString();
        QString arrivalAirport = query.value(12).toString();
        QString departureTime = query.value(13).toString();
        QString arrivalTime = query.value(14).toString();
        double price = query.value(15).toDouble();
        QString isTransfer = query.value(16).toString();
        QString services = query.value(17).toString();
        double servicePrice = query.value(18).toDouble();

        // 如果 journeyID 改变了，意味着是一个新的行程，我们插入行程总览信息
        if (journeyID != currentJourneyID) {
            currentJourneyID = journeyID;
            row = ui->bookingTableWidget->rowCount();
            ui->bookingTableWidget->insertRow(row);


            // 显示 journey 总览信息
            ui->bookingTableWidget->setItem(row, 0, new QTableWidgetItem(startCity+"---->"+endCity));
            ui->bookingTableWidget->setItem(row, 1, new QTableWidgetItem(traveldate));
            ui->bookingTableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(totalPrice)+"元"));  // 用于标识这是 journey 总览

            // 退票和改签按钮
            QPushButton *rescheduleButton = new QPushButton("退订");
            connect(rescheduleButton, &QPushButton::clicked, this, [=]() { cancelBooking(bookingID); });
            ui->bookingTableWidget->setCellWidget(row, 3, rescheduleButton);

            // 另起一行用于航段显示
            row++;
        }

        // 使用 journeyID 和航班号的组合来唯一标识 segment，避免重复显示相同航段
        QString segmentKey = QString::number(journeyID) + "-" + flightNumber;

        // 检查这个航段是否已经插入过
        if (!displayedSegments.contains(segmentKey)) {
            displayedSegments.insert(segmentKey);  // 插入标记，避免后续重复

            // 添加航段信息
            ui->bookingTableWidget->insertRow(row);

            // 设置航段信息到表格中
            ui->bookingTableWidget->setItem(row, 3, new QTableWidgetItem(flightNumber));  // 航班号
            ui->bookingTableWidget->setItem(row, 4, new QTableWidgetItem(airline));       // 航空公司
            ui->bookingTableWidget->setItem(row, 5, new QTableWidgetItem(fromCity));      // 出发城市
            ui->bookingTableWidget->setItem(row, 6, new QTableWidgetItem(toCity));        // 到达城市
            ui->bookingTableWidget->setItem(row, 7, new QTableWidgetItem(departureAirport));  // 起飞机场
            ui->bookingTableWidget->setItem(row, 8, new QTableWidgetItem(arrivalAirport));    // 降落机场
            ui->bookingTableWidget->setItem(row, 9, new QTableWidgetItem(departureTime));     // 起飞时间
            ui->bookingTableWidget->setItem(row, 10, new QTableWidgetItem(arrivalTime));       // 到达时间
            ui->bookingTableWidget->setItem(row, 11, new QTableWidgetItem(QString::number(price)));  // 价格


            // 改签按钮
            QPushButton *rescheduleButton = new QPushButton("改签");
            connect(rescheduleButton, &QPushButton::clicked, this, [=]() {
                int currentSegmentID=segmentID;
                rescheduleBooking(currentSegmentID, bookingID, fromCity, toCity); });
            ui->bookingTableWidget->setCellWidget(row, 12, rescheduleButton);

            QPushButton *serviceButton = new QPushButton("服务选项");
            connect(serviceButton, &QPushButton::clicked, this, [=]() {
                int SegmentID=segmentID;
                configureSpecialServices(SegmentID); }); // 打开服务配置窗口
            ui->bookingTableWidget->setCellWidget(row, 13, serviceButton);


            ui->bookingTableWidget->setItem(row, 14, new QTableWidgetItem(QString::number(servicePrice)));

            row++;
        }
    }
}

// 退票操作
void UserManagementWidget::cancelBooking(int bookingID) {
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认退票", "您确定要退订此航班吗？", QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        QSqlDatabase db = AccountManager::getDatabase();
        if (!db.isOpen() && !db.open()) {
            qDebug() << "Failed to open database: " << db.lastError().text();
            return;
        }

        QSqlQuery query(db);

        // Step 1: 获取 journey_id
        query.prepare("SELECT journey_id FROM user_bookings WHERE booking_id = ?");
        query.addBindValue(bookingID);
        if (!query.exec() || !query.next()) {
            qDebug() << "Failed to retrieve journey_id for bookingID: " << bookingID << ", error: " << query.lastError().text();
            return;
        }

        int journeyID = query.value(0).toInt();
        qDebug() << "Successfully retrieved journey_id: " << journeyID;

        // Step 2: 删除 flight_segments 中的相关记录
        QSqlQuery deleteSegmentsQuery(db);
        deleteSegmentsQuery.prepare("DELETE FROM flight_segments WHERE journey_id = ?");
        deleteSegmentsQuery.addBindValue(journeyID);
        if (!deleteSegmentsQuery.exec()) {
            qDebug() << "Failed to delete flight segments for journey_id: " << journeyID << ", error: " << deleteSegmentsQuery.lastError().text();
            return;
        }

        // Step 3: 删除 user_bookings 中的相关记录
        QSqlQuery deleteBookingQuery(db);
        deleteBookingQuery.prepare("DELETE FROM user_bookings WHERE booking_id = ?");
        deleteBookingQuery.addBindValue(bookingID);
        if (!deleteBookingQuery.exec()) {
            qDebug() << "Failed to delete user booking for booking_id: " << bookingID << ", error: " << deleteBookingQuery.lastError().text();
            return;
        }

        // Step 4: 删除 journeys 中的记录
        QSqlQuery deleteJourneyQuery(db);
        deleteJourneyQuery.prepare("DELETE FROM journeys WHERE journey_id = ?");
        deleteJourneyQuery.addBindValue(journeyID);
        if (!deleteJourneyQuery.exec()) {
            qDebug() << "Failed to delete journey for journey_id: " << journeyID << ", error: " << deleteJourneyQuery.lastError().text();
            return;
        }

        qDebug() << "退票成功: " << bookingID;
        QMessageBox::information(this, "退票成功", "您已成功退票。");
        emit deletingCompleted();
        qDebug() << "bookingChanged signal emitted.";
        // 刷新订票历史
        loadBookingHistory();
    }
}



// 改签操作
void UserManagementWidget::rescheduleBooking(int segmentID, int bookingID, QString fromCity, QString toCity) {
    int sID = segmentID;
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认改签", "您确定要改签此航班吗？", QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        QSqlDatabase db = AccountManager::getDatabase();
        if (!db.isOpen() && !db.open()) {
            QMessageBox::critical(this, "数据库错误", "无法连接到数据库：" + db.lastError().text());
            return;
        }

        QSqlQuery journeyQuery(db);
        journeyQuery.prepare("SELECT journey_id FROM user_bookings WHERE booking_id = :bookingID");
        journeyQuery.bindValue(":bookingID", bookingID);

        if (!journeyQuery.exec() || !journeyQuery.next()) {
            QMessageBox::warning(this, "错误", "无法获取对应的旅程ID：" + journeyQuery.lastError().text());
            return;
        }

        int journeyID = journeyQuery.value(0).toInt();

        // 获取航班路径
        QList<FlightJourney> flightJourneys = g.findAllPaths(fromCity, toCity, 0);

        if (flightJourneys.isEmpty()) {
            QMessageBox::information(this, "没有航班", "没有找到从 " + fromCity + " 到 " + toCity + " 的航班。");
            return;
        }

        // 去重逻辑
        QSet<QString> uniquePaths;
        QList<FlightJourney> uniqueFlightJourneys;
        for (const auto& journey : flightJourneys) {
            QString pathSignature;
            for (const auto& segment : journey.segments) {
                pathSignature += segment.flightNumber + "->";
            }

            if (!uniquePaths.contains(pathSignature)) {
                uniquePaths.insert(pathSignature);
                uniqueFlightJourneys.append(journey);
            }
        }

        QDialog* selectionDialog = new QDialog(this);
        QVBoxLayout* dialogLayout = new QVBoxLayout(selectionDialog);
        QTableWidget* flightTableWidget = new QTableWidget(uniqueFlightJourneys.size(), 8, selectionDialog);
        flightTableWidget->setMinimumSize(1100, 800);
        // 设置表头
        QStringList headers = {"航班号", "航空公司", "起飞机场", "降落机场", "起飞时间", "到达时间", "价格", "选择"};
        flightTableWidget->setHorizontalHeaderLabels(headers);

        // 填充表格
        flightTableWidget->clearContents();  // 确保没有残留内容
        for (int i = 0; i < uniqueFlightJourneys.size(); ++i) {
            const FlightJourney& journey = uniqueFlightJourneys[i];

            QString flightNumber = journey.segments.isEmpty() ? "N/A" : journey.segments.first().flightNumber;
            QString airline = journey.segments.isEmpty() ? "N/A" : journey.segments.first().airline;
            QString departureAirport = journey.segments.isEmpty() ? "N/A" : journey.segments.first().departureAirport;
            QString arrivalAirport = journey.segments.isEmpty() ? "N/A" : journey.segments.last().arrivalAirport;
            QString departureTime = journey.segments.isEmpty() ? "N/A" : journey.segments.first().departureTime.toString("HH:mm");
            QString arrivalTime = journey.segments.isEmpty() ? "N/A" : journey.segments.last().arrivalTime.toString("HH:mm");
            QString segmentPrice = journey.segments.isEmpty() ? "N/A" : QString::number(journey.segments.first().price, 'f', 2);

            flightTableWidget->setItem(i, 0, new QTableWidgetItem(flightNumber));
            flightTableWidget->setItem(i, 1, new QTableWidgetItem(airline));
            flightTableWidget->setItem(i, 2, new QTableWidgetItem(departureAirport));
            flightTableWidget->setItem(i, 3, new QTableWidgetItem(arrivalAirport));
            flightTableWidget->setItem(i, 4, new QTableWidgetItem(departureTime));
            flightTableWidget->setItem(i, 5, new QTableWidgetItem(arrivalTime));
            flightTableWidget->setItem(i, 6, new QTableWidgetItem(segmentPrice));

            QPushButton* selectButton = new QPushButton("选择");
            connect(selectButton, &QPushButton::clicked, this, [=, &journey]() {
                FlightSegment selectedSegment = journey.segments.first();
                updateSegmentInDatabase(sID, selectedSegment);
                updateJourneyInDatabase(journeyID);
                loadBookingHistory();
                selectionDialog->accept();
            });
            flightTableWidget->setCellWidget(i, 7, selectButton);
        }

        dialogLayout->addWidget(flightTableWidget);
        selectionDialog->setLayout(dialogLayout);
        selectionDialog->exec();
    }
}


void loadAllFlights(const QString& folderPath) {
    QDir directory(folderPath);
    QStringList files = directory.entryList(QStringList() << "*.txt", QDir::Files);
    QSet<QString> citySet;

    for (const QString& fileName : files) {
        QStringList cityNames = fileName.split("-");
        if (cityNames.size() < 2) {
            qDebug() << "文件名格式错误: " << fileName;
            continue;
        }
        QString fromCity = cityNames[0].trimmed();
        QString toCity = cityNames[1].replace(".txt", "").trimmed();

        if (!citySet.contains(fromCity)) {
            g.addCity(fromCity);
            citySet.insert(fromCity);
        }
        if (!citySet.contains(toCity)) {
            g.addCity(toCity);
            citySet.insert(toCity);
        }

        QString filePath = folderPath + "/" + fileName;
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "无法打开文件: " << filePath;
            continue;
        }

        QTextStream in(&file);
        in.setCodec("GB18030");
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            QStringList parts = line.split("/");

            if (parts.size() < 8) {
                qDebug() << "文件格式错误: " << line;
                continue;
            }
            QString airline = parts[0].trimmed();
            QString flightNumber = parts[1].trimmed();
            QString deAirport = parts[2].trimmed();
            QString arrAirport = parts[3].trimmed();

            // 检查是否读取了空字符串作为城市名称
            if (deAirport.isEmpty() || arrAirport.isEmpty()) {
                qDebug() << "城市信息缺失: " << line;
                continue;
            }

            QTime deTime = QTime::fromString(parts[4].trimmed(), "HH:mm");
            QTime arrTime = QTime::fromString(parts[5].trimmed(), "HH:mm");
            double price = parts[6].trimmed().toDouble();
            double occupancy = parts[7].trimmed().remove("%").toDouble();

            if (!deTime.isValid() || !arrTime.isValid()) {
                //qDebug() << "时间格式错误: " << line;
                continue;
            }

            double timeC = deTime.secsTo(arrTime) / 3600.0;
            if (timeC < 0) {
                timeC += 24.0;
            }

            auto details = std::make_shared<FlightDetails>(airline, flightNumber, deAirport, arrAirport, deTime, arrTime, QDate::currentDate(), occupancy);
            g.addEdge(fromCity, toCity, airline, flightNumber, deAirport, arrAirport, deTime, arrTime, price, occupancy, timeC, QDate::currentDate());

            /*qDebug() << "成功加载航班: " << airline << flightNumber << deAirport << "->" << arrAirport
                     << " 起飞时间: " << deTime.toString()
                     << " 降落时间: " << arrTime.toString()
                     << " 价格: " << price
                     << " 上座率: " << occupancy;*/
        }
    }
}


int UserManagementWidget::getSegmentIDFromDatabase(const FlightSegment& segment) {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return -1;  // 如果失败返回 -1
    }

    QSqlQuery query(db);

    // 打印出查询的 SQL 语句，调试用
    QString sql = "SELECT segment_id FROM flight_segments WHERE flight_number = :flightNumber "
                  "AND departure_time = :departureTime";
    qDebug() << "Executing SQL: " << sql;

    query.prepare(sql);
    query.bindValue(":flightNumber", segment.flightNumber);
    //query.bindValue(":departureAirport", segment.departureAirport);
    query.bindValue(":departureTime", segment.departureTime.toString("HH:mm"));  // 使用带秒的格式

    qDebug() << "Binding Parameters: "
             << "Flight Number: " << segment.flightNumber
                //<< "Departure Airport: " << segment.departureAirport
             << "Departure Time: " << segment.departureTime.toString("HH:mm");

    if (query.exec() && query.next()) {
        int segmentID = query.value(0).toInt();
        qDebug() << "Retrieved segmentID: " << segmentID;
        return segmentID;
    } else {
        qDebug() << "Failed to retrieve segmentID: " << query.lastError().text();
        return -1;  // 如果查询失败返回 -1
    }
}




void UserManagementWidget::updateJourneyInDatabase(int journeyID) {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    // 获取对应 journey 的信息
    FlightJourney journey = getJourneyByID(journeyID);

    // 重新计算总价格和总时间
    double totalPrice = journey.getTotalPrice();
    qDebug()<<"updated totalPrice is:"<<totalPrice;
    int totalTime = journey.getTotalTime();

    QSqlQuery query(db);

    // 更新 journey 的总价格和总时间
    query.prepare("UPDATE journeys SET total_price = :totalPrice, total_time = :totalTime WHERE journey_id = :journeyID");
    query.bindValue(":totalPrice", totalPrice);
    query.bindValue(":totalTime", totalTime);
    query.bindValue(":journeyID", journeyID);

    if (!query.exec()) {
        qDebug() << "Failed to update journey: " << query.lastError().text();
    } else {
        qDebug() << "Journey updated successfully";
    }
}

FlightJourney UserManagementWidget::getJourneyByID(int journeyID) {
    FlightJourney journey;

    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return journey;
    }

    QSqlQuery query(db);
    query.prepare("SELECT * FROM flight_segments WHERE journey_id = :journeyID");
    query.bindValue(":journeyID", journeyID);

    if (!query.exec()) {
        qDebug() << "Failed to query flight_segments: " << query.lastError().text();
        return journey;
    }

    while (query.next()) {
        FlightSegment segment;
        segment.price = query.value("price").toDouble();
        journey.segments.append(segment);  // 填充航段数据
    }

    qDebug() << "Loaded journey with segments count:" << journey.segments.size();
    return journey;
}

void UserManagementWidget::updateSegmentInDatabase(int segmentID, const FlightSegment& selectedSegment) {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    QSqlQuery query(db);

    // 使用 UPDATE 语句更新指定 segment 的信息
    query.prepare("UPDATE flight_segments SET flight_number = :flightNumber, "
                  "airline = :airline, from_city = :fromCity, to_city = :toCity, "
                  "departure_airport = :departureAirport, arrival_airport = :arrivalAirport, "
                  "departure_time = :departureTime, arrival_time = :arrivalTime, price = :price, "
                  "is_transfer = :isTransfer WHERE segment_id = :segmentID");

    query.bindValue(":flightNumber", selectedSegment.flightNumber);
    query.bindValue(":airline", selectedSegment.airline);
    query.bindValue(":fromCity", selectedSegment.fromCity);
    query.bindValue(":toCity", selectedSegment.toCity);
    query.bindValue(":departureAirport", selectedSegment.departureAirport);
    query.bindValue(":arrivalAirport", selectedSegment.arrivalAirport);
    query.bindValue(":departureTime", selectedSegment.departureTime.toString("HH:mm"));
    query.bindValue(":arrivalTime", selectedSegment.arrivalTime.toString("HH:mm"));
    query.bindValue(":price", selectedSegment.price);
    query.bindValue(":isTransfer", selectedSegment.isTransfer ? "Yes" : "No");
    query.bindValue(":segmentID", segmentID);

    qDebug()<<"the selected segment's price is:"<<selectedSegment.price;

    if (!query.exec()) {
        qDebug() << "Failed to update segment: " << query.lastError().text();
    } else {
        qDebug() << "Segment updated successfully";
    }
}


void UserManagementWidget::on_mapButton_clicked()
{
    emit(deletingCompleted());
}

void UserManagementWidget::configureSpecialServices(int segmentID) {
    QDialog *serviceDialog = new QDialog(this);
    serviceDialog->setWindowTitle("配置服务");

    QVBoxLayout *layout = new QVBoxLayout(serviceDialog);

    // 服务选项和价格
    QCheckBox *mealService = new QCheckBox("鸡肉帕尼尼 (¥20)");
    QCheckBox *loungeService = new QCheckBox("贵宾室服务 (¥100)");
    QCheckBox *extraBaggage = new QCheckBox("额外行李 (¥200)");

    QLabel *totalPriceLabel = new QLabel("总价格: ¥0");

    layout->addWidget(mealService);
    layout->addWidget(loungeService);
    layout->addWidget(extraBaggage);
    layout->addWidget(totalPriceLabel);

    QPushButton *confirmButton = new QPushButton("确认");
    layout->addWidget(confirmButton);

    // 加载当前服务状态
    loadSpecialServices(segmentID, mealService, loungeService, extraBaggage);

    // 动态更新总价格
    auto updateTotalPrice = [=]() {
        double totalPrice = 0;
        if (mealService->isChecked()) totalPrice += 20;
        if (loungeService->isChecked()) totalPrice += 100;
        if (extraBaggage->isChecked()) totalPrice += 200;
        totalPriceLabel->setText(QString("总价格: ¥%1").arg(totalPrice));
    };

    connect(mealService, &QCheckBox::stateChanged, updateTotalPrice);
    connect(loungeService, &QCheckBox::stateChanged, updateTotalPrice);
    connect(extraBaggage, &QCheckBox::stateChanged, updateTotalPrice);

    // 保存选择
    connect(confirmButton, &QPushButton::clicked, this, [=]() {
        double totalPrice = 0;
        if (mealService->isChecked()) totalPrice += 20;
        if (loungeService->isChecked()) totalPrice += 100;
        if (extraBaggage->isChecked()) totalPrice += 200;

        saveSpecialServices(segmentID, mealService->isChecked(), loungeService->isChecked(), extraBaggage->isChecked(), totalPrice);
        serviceDialog->accept();
    });

    serviceDialog->setLayout(layout);
    serviceDialog->exec();
}

void UserManagementWidget::saveSpecialServices(int segmentID, bool meal, bool lounge, bool baggage, double totalPrice) {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    QStringList services;
    if (meal) services << "meal";
    if (lounge) services << "lounge";
    if (baggage) services << "baggage";

    QString serviceString = services.join(",");

    QSqlQuery query(db);
    query.prepare("UPDATE flight_segments SET special_services = :services, service_price = :price WHERE segment_id = :segmentID");
    query.bindValue(":services", serviceString);
    query.bindValue(":price", totalPrice);
    query.bindValue(":segmentID", segmentID);

    if (!query.exec()) {
        qDebug() << "Failed to save special services: " << query.lastError().text();
    } else {
        qDebug() << "Special services updated for segment ID: " << segmentID << " with price: " << totalPrice;
    }
    loadBookingHistory();
}

void UserManagementWidget::loadSpecialServices(int segmentID, QCheckBox *mealService, QCheckBox *loungeService, QCheckBox *extraBaggage) {
    QSqlDatabase db = AccountManager::getDatabase();
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Failed to open database: " << db.lastError().text();
        return;
    }

    QSqlQuery query(db);
    query.prepare("SELECT special_services FROM flight_segments WHERE segment_id = :segmentID");
    query.bindValue(":segmentID", segmentID);

    if (!query.exec() || !query.next()) {
        qDebug() << "Failed to load special services: " << query.lastError().text();
        return;
    }

    QString services = query.value(0).toString();
    mealService->setChecked(services.contains("meal"));
    loungeService->setChecked(services.contains("lounge"));
    extraBaggage->setChecked(services.contains("baggage"));
}
